package com.le.basic.Sort;

import org.junit.Test;

import java.util.Arrays;

public class MergeSortTest {
    public static void sortMerge(int[] arr){
        mergeSorted(arr,0,arr.length-1);
    }


    public static void mergeSorted(int[] arr, int left, int right) {
        if (left == right) {
            return;
        }
        int mid = (left + right) / 2;
        mergeSorted(arr, left, mid);
        mergeSorted(arr, mid + 1, right);
        merge(arr, left, right, mid);
    }

    private static void merge(int[] arr, int left, int right, int mid) {
        int[] temp = new int[right - left + 1];
        int p1 = left;
        int p2 = mid + 1;
        int i = 0;
        while (p1 <= mid && p2 <= right) {
            temp[i++] = arr[p1] <= arr[p2] ? arr[p1++] : arr[p2++];
        }
        while (p1 <= mid) {
            temp[i++] = arr[p1++];
        }
        while (p2 <= right) {
            temp[i++] = arr[p2++];
        }

        for (int j = 0; j < temp.length; j++) {
            arr[left + j] = temp[j];
        }
    }

    @Test
    public void test(){
        int[] arr = {2,1,6,3,0};
        sortMerge(arr);
        System.out.println(Arrays.toString(arr));
    }
}
